package com.fy56.platform.goodsTracking.quartz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fy56.model.ResultModel;
import com.fy56.platform.goodsTracking.commons.security.MD5;
import com.fy56.platform.goodsTracking.commons.unit.DateTimeUtil;
import com.fy56.platform.goodsTracking.commons.unit.WebUtils;
import com.fy56.platform.goodsTracking.model.*;
import com.fy56.platform.goodsTracking.service.GoodstrackedRecordPublicServie;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by XTK on 2016-11-28.
 */
@Service
public class JrptUpload {
    @Autowired
    private GoodstrackedRecordPublicServie subService;
    static Logger log = Logger.getLogger(JrptUpload.class);




    public String getCollectionType(String type){
        //F6 现金 银行 直发
        //腾云 0=现金发放 1=银行发放 2=直接发放  3=三方支付
        if("现金".equals(type)){
            type="0";
        }else  if("银行".equals(type)){
            type="1";
        }else  if("直发".equals(type)){
            type="2";
        }else{
            type="3";
        }
        return type;

    }
    public String getjobType(String type){
        //F6 装车配载、提货单、转营业部、直接配送、送货派车、中转派车
        //腾云 派车类型 0.装车配载1.市内提货单2.预受理单派车3.直接配送派车4.送货派车5.装营业部派车6.转非专线派车
        if("装车配载".equals(type)){
            type="0";
        }else  if("提货单".equals(type)){
            type="1";
        }else  if("转营业部".equals(type)){
            type="5";
        }else  if("直接配送".equals(type)){
            type="3";
        }else  if("送货派车".equals(type)){
            type="4";
        }else  if("中转派车".equals(type)){
            type="6";
        }else  if("预受理派车".equals(type)){
            type="2";
        }
        return type;

    }
    public ResultModel uploadCar(String url,TransportbillmasterPublic car,List<TransportbillDetailsPublic> mx) {
        Map<String, Object> param = Maps.newHashMap();
        ResultModel reModel=new ResultModel();
        try{
            String result="";
            List mxList = new ArrayList();
            if (mx!=null&&mx.size()>0){
                for(int i=0;i<mx.size();i++){
                    String resquestedLoadingDateTime=mx.get(i).getConsignmentbilldate()+"";
                    if (resquestedLoadingDateTime!=null&&resquestedLoadingDateTime.length()>=19){
                        resquestedLoadingDateTime=resquestedLoadingDateTime.substring(0,19);
                    }
                    Map<String, String> pram = Maps.newHashMap();
                    pram.put("trackingNo",mx.get(i).getTrackingNo());
                    pram.put("shippingNoteNumber",mx.get(i).getConsignmentbillnumber());//: "票号",
                    pram.put("consignorName",mx.get(i).getConsignee());//: "发货人",
                    pram.put("consignorTelephoneNumber",mx.get(i).getConsignormobiletelephone());//: "发货人电话",
                    pram.put("resquestedLoadingDateTime",resquestedLoadingDateTime);//: "发货时间",
                    pram.put("placeOfLoading",mx.get(i).getConsignoraddress());//: "发货地址",
                    pram.put("consigneeName",mx.get(i).getConsignee());//: "收货人",
                    pram.put("consigneeTelephoneNumber",mx.get(i).getConsigneemobiletelephone());//: "收货人电话",
                    pram.put("goodsReceiptPlace",mx.get(i).getConsigneeaddress());//: "收货详细地址",
                    pram.put("totalNumberOfPackages",mx.get(i).getTotalnumberofpackages()+"");//: 总件数,
                    pram.put("totalWeight",mx.get(i).getTotalweight()+"");//: 重量合计,
                    pram.put("totalVolume",mx.get(i).getTotalvolume()+"");//: 体积合计,
                    pram.put("freightAmount",mx.get(i).getTotaltransportcost()+"");//: 运费,
                    pram.put("collectingFees",mx.get(i).getCollectiongoodsvalue()+"");//: 代收货款
                    mxList.add(pram);
                }
            }
            Map<String, Object> params = Maps.newHashMap();
            Map<String, String> pram1 = Maps.newHashMap();
            Map<String, String> pram2 = Maps.newHashMap();
            Map<String, String> pram3 = Maps.newHashMap();
            List list = new ArrayList();
            pram1.put("code","freight");
            pram1.put("money",car.getTotaltransportcost()+"");//运费
            list.add(pram1);
            pram2.put("code","initialMoney");
            pram2.put("money",car.getCollectiongoodsvalue()+"");//代收
            list.add(pram2);
            pram3.put("code","totalSendcarFreight");
            pram3.put("money",car.getTotalfare()+"");//给车运费
            list.add(pram3);
            params.put("jobOrderNumber",car.getTransportbillnumber());//派车编号
            params.put("jobType",getjobType(car.getTransportbilltype()));//派车类型 数字
            String fcrq=car.getTransportstartdate()+"";
            if(fcrq!=null&&fcrq.length()>19){
                fcrq = fcrq.substring(0,19);
            }
            params.put("vehicleDispactionDate",fcrq);//发车日期
            String endCompanyCode="20665";
            if(car.getEndcompanycode()!=null&&car.getEndcompanycode().length()!=0){
                endCompanyCode=car.getEndcompanycode();
            }
            String startCompanyCode="20665";
            if(car.getStartcompanycode()!=null&&car.getStartcompanycode().length()!=0){
                startCompanyCode=car.getStartcompanycode();
            }
            params.put("startCompanyCode",startCompanyCode);//发货企业编码
            params.put("endCompanyCode",endCompanyCode);//到货企业编码
            params.put("placeOfLoading",car.getTransportbeginplace());//发车地点
            params.put("placeOfDischarge",car.getReceivecompany());//卸车地点
            String vehicleNumber="0";
            if(car.getCarnumber()!=null&&car.getCarnumber().length()>0){
                vehicleNumber=car.getCarnumber();
            }
            params.put("vehicleNumber",vehicleNumber);//车号
            String driver = "司机";
            if(car.getDrivername()!=null&&car.getDrivername().length()!=0){
                driver =car.getDrivername();
            }
            params.put("driver",driver);//司机姓名
            String driverPhone = "0";
            if(car.getDrivertelephone()!=null&&car.getDrivertelephone().length()!=0){
                driverPhone =car.getDrivertelephone();
            }
            params.put("driverPhone",driverPhone);//司机电话
            String supercargo = "押运员";
            if(car.getCopilotname()!=null&&car.getCopilotname().length()!=0){
                supercargo=car.getCopilotname();
            }
            params.put("supercargo",supercargo);//腾云：押运员   F6 暂用承运员
            String supercargoPhone = "0";
            if(car.getCopilottelephone()!=null&&car.getCopilottelephone().length()!=0){
                supercargoPhone=car.getCopilottelephone();
            }
            params.put("supercargoPhone",supercargoPhone);//押运员电话
            params.put("orderCount",car.getConsignmentbillcount()+"");//订单总数
            params.put("totalNumber",car.getTotalnumberofpackages()+"");//总件数
            params.put("totalCube",car.getTotalvolume()+"");//总体积
            params.put("totalWeight",car.getTotalweight()+"");//总重量
            params.put("moneyNodes",list);
            params.put("orderNodes",mxList);//新加派车明细

            param.put("jsonData",params);
            param.put("funOption","add");
            param.put("tenant",car.getTenant());
            String password="";
            if(car.getTenantpass()!=null&&car.getTenantpass().length()!=0){
                password=MD5.digest(car.getTenantpass());
            }
            if(password!=null&&password.length()!=0){
                car.setTenantpass(password.toLowerCase());
            }
            param.put("tenantPass",car.getTenantpass());





//            String importStr = "{'jsonData':{'jobOrderNumber':'" + car.getTransportbillnumber()
//                    + "','jobType':'" + getjobType(car.getTransportbilltype())
//                    + "','vehicleDispactionDate':'" + car.getTransportstartdate()
//                    + "','endCompanyCode':'" + car.getEndcompanycode()
//                    + "','placeOfLoading':'"+ car.getTransportbeginplace()
//                    + "','placeOfDischarge':'"+ car.getReceivecompany()
//                    + "','vehicleNumber':'" + car.getCarnumber()
//                    + "','driver':'" + car.getDrivername()
//                    + "','driverPhone':'" + car.getDrivertelephone()
//                    + "','supercargo':'" + car.getCopilotname()
//                    + "','supercargoPhone':'" + car.getCopilottelephone()
//                    + "','orderCount':'" + car.getConsignmentbillcount()
//                    + "','totalNumber':'" + car.getTotalnumberofpackages()
//                    + "','totalCube':'" + car.getTotalvolume()
//                    + "','totalWeight':'" +car.getTotalweight()
//                    + "','moneyNodes':["
//                    + "{'code':'freight','money':'"+ car.getTotaltransportcost() +"'}"
//                    + ",{'code':'initialMoney ','money':'"+ car.getCollectiongoodsvalue()+"'}"
//                    + ",{'code':'totalSendcarFreight','money':'"+ car.getTotalfare() +"'}"
//                    + "]},'funOption':'add"
//                    + "','trackingNo':'"
//                    + "','tenant':'" + car.getTenant()
//                    + "','tenantPass':'" + car.getTenantpass()
//                    + "'}";
            //            p.put("param",importStr);


//            Map<String, String> p = Maps.newHashMap();
//            p.put("param",JSONObject.toJSONString(param));
//            p.put("billType","sendCar");
//            p.put("funOption","add");
//            log.info(" ---doUpload 参数:" + JSON.toJSONString(p) );
//                HttpRequest mRequest = HttpRequest.post(url+"/ohmPublicQueue/addQueue" , p, true);
//                mRequest.header("Content-type", "application/x-www-form-urlencoded");
//                result = mRequest.body();
//                log.info(" ---doUpload 结果:" + result);

//            CAR_URL
            com.fy56.utils.TrackCenterSender.configSendUrl(url);
             reModel=com.fy56.utils.TrackCenterSender.addSendcar(JSONObject.toJSONString(param));
            log.info(" --补传参数:" + JSONObject.toJSONString(param)+" 结果:"+JSONObject.toJSONString(reModel));

        }catch (Exception e){
            log.info("--补传派车记录失败,param："+JSONObject.toJSONString(car)+" error:"+e.getMessage());
        }
        return reModel;
    }
    public ResultModel uploadCollection(String url,CollectiongoodsvalueaccountPublic collection) {
        Map<String, Object> param = Maps.newHashMap();
        ResultModel reModel=null;
        try{
            String result="";
            Map<String, Object> params = Maps.newHashMap();
            Map<String, String> pram1 = Maps.newHashMap();
            Map<String, String> pram2 = Maps.newHashMap();
            Map<String, String> pram3 = Maps.newHashMap();
            Map<String, String> pram4 = Maps.newHashMap();
            Map<String, String> pram5 = Maps.newHashMap();
            Map<String, String> pram6 = Maps.newHashMap();
            Map<String, String> pram7 = Maps.newHashMap();
            Map<String, String> pram8 = Maps.newHashMap();
            Map<String, String> pram9 = Maps.newHashMap();
            try{
                collection=(CollectiongoodsvalueaccountPublic) killNull(collection);
            }catch (Exception e){

            }

            List list = new ArrayList();
            pram1.put("code","overdueFee");
            pram1.put("money",collection.getExceedextracost()+"");//超期手续费
            list.add(pram1);
            pram2.put("code","reportFee");
            pram2.put("money",collection.getLoseextracost()+"");//挂失手续费
            list.add(pram2);
            pram3.put("code","fee");
            pram3.put("money",(collection.getExtracostovercharge().subtract(collection.getExtracostdecreasecharge()))+"");//手续费
            list.add(pram3);
            pram4.put("code","initialMoney");
            pram4.put("money",collection.getCollectiongoodsvalue()+"");//代收货款
            list.add(pram4);
            pram5.put("code","deductibleFreight");
            pram5.put("money",collection.getDeductiontransportcost()+"");//回扣运费
            list.add(pram5);
            pram6.put("code","reductionMoney");
            pram6.put("money",collection.getCollectiongoodsvaluedec()+"");//拒付货款
            list.add(pram6);
            pram7.put("code","insureFee");
            pram7.put("money",collection.getSettlementinsurancecost()+"");//保险费
            list.add(pram7);
            pram8.put("code","paymentMoney");
            pram8.put("money",collection.getPaymentmoney()+"");//应付代收
            list.add(pram8);
            pram9.put("code","noteFee");
            pram9.put("money",collection.getShortmessagecharge()+"");//信息费
            list.add(pram9);
            params.put("uniqueOrderNo",collection.getCollectiongoodsvalueaccountid());//唯一顺序号
            params.put("shippingNoteNumber",collection.getConsignmentbillnumber());//票号
            params.put("originalDocumentNumber",collection.getManualnumber()+"");//手工单号
            params.put("goodsNumber",collection.getGoodsnumber());//货号
            String hkrq = "";
            if (collection.getReturnmoneydate()!= null){
                if (collection.getReturnmoneydate().toString().length()>19){
                    hkrq=collection.getReturnmoneydate().toString().substring(0,19);
                } else {
                    hkrq=collection.getReturnmoneydate().toString();
                }
            }
            String kprq = "";
            if (collection.getConsignmentbilldate()!= null){
                if (collection.getConsignmentbilldate().toString().length()>19){
                    kprq=collection.getConsignmentbilldate().toString().substring(0,19);
                } else {
                    kprq=collection.getConsignmentbilldate().toString();
                }
            }
            params.put("takeTime",hkrq);//回款日期
            String fkrq = "";
            if (collection.getGivedate()!= null){
                if (collection.getGivedate().toString().length()>19){
                    fkrq=collection.getGivedate().toString().substring(0,19);
                } else {
                    fkrq=collection.getGivedate().toString();
                }
            }
            String  consignortelephone= collection.getConsignortelephone();
            if(consignortelephone==null||consignortelephone.length()==0){
                consignortelephone="0";
            }

            params.put("paymentTime",fkrq);//支付日期
            params.put("consignmentTime",kprq);//开票日期
            params.put("cardNo",collection.getOnecardcode()+"");//一卡通号
            params.put("bankCodeNo",collection.getAccount());//银行卡号
            String consignee="收货人";
            if(collection.getConsignee()!=null&&collection.getConsignee().length()!=0){
                consignee=collection.getConsignee();
            }
            params.put("consignee",consignee);//收货人
            String consigneemobiletelephone="0";
            if(collection.getConsigneemobiletelephone()!=null&&collection.getConsigneemobiletelephone().length()!=0){
                consigneemobiletelephone= collection.getConsigneemobiletelephone();
            }
            params.put("consigneePhone",consigneemobiletelephone);//收货人电话
            String consignor="发货人";
            if(collection.getConsignor()!=null&&collection.getConsignor().length()!=0){
                consignor=collection.getConsignor();
            }
            params.put("consignor",consignor);//发货人
            params.put("consigneePhone",consignortelephone);//发货人电话
            String accountUserName="领取人";
            if(collection.getAccountholder()!=null&&collection.getAccountholder().length()!=0){
                accountUserName=collection.getAccountholder();
            }
            params.put("accountUserName",accountUserName);//领取人
            String accountUserPhone="0";
            if(collection.getShortmessagemobiletelephone()!=null&&collection.getShortmessagemobiletelephone().length()!=0){
                accountUserPhone=collection.getShortmessagemobiletelephone()+"";
            }
            params.put("accountUserPhone",accountUserPhone);//领取人电话
            params.put("payType",getCollectionType(collection.getGivetype()));//0=现金发放 1=银行发放 2=直接发放  3=三方支付
            params.put("thirdPartyCompany","");//保留 暂时为空
            params.put("moneyNodes",list);
            param.put("jsonData",params);
            String funOption="add";
            if("2".equals(collection.getFlag())){
                funOption="delete";
                try{
                    subService.updateCollectionsetId(collection.getCollectiongoodsvalueaccountid());
                }catch (Exception e){
                    log.error("updateCollectionsetId",e);
                }
            }
            param.put("funOption",funOption);
            param.put("tenant",collection.getTenant());
            String password="";
            if(collection.getTenantpass()!=null&&collection.getTenantpass().length()!=0){
                password=MD5.digest(collection.getTenantpass());
            }
            if(password!=null&&password.length()!=0){
                collection.setTenantpass(password.toLowerCase());
            }
            param.put("tenantPass",collection.getTenantpass());


             reModel=com.fy56.utils.TrackCenterSender.addCollectionPay(JSONObject.toJSONString(param));
            log.info(" --addCollectionPay参数:" + JSONObject.toJSONString(param)+" 结果:"+JSONObject.toJSONString(reModel));
            if(100==reModel.getCode()){
                TyResultModel content= JSON.parseObject(reModel.getObject().toString(),TyResultModel.class);
                if("SUCCESS".equals(content.getReturnCode())){
                    subService.updateCollection(content.getTrackingNo(),collection.getOrganizationcode()+"",collection.getCollectiongoodsvalueaccountid());
                }
            }else{
                subService.updateCollection("失败"+reModel.getMessage(),collection.getOrganizationcode()+"",collection.getCollectiongoodsvalueaccountid());
            }

        }catch (Exception e){
            log.info("--上传代收记录失败,param："+JSONObject.toJSONString(collection)+" error:"+e.getMessage());
        }
        return  reModel;
    }
    public static Object killNull(Object object) throws Exception {
        //遍历object类 成员为String类型 属性为空的全部替换为""
        Field[] fields = object.getClass().getDeclaredFields();

        for (int i = 0; i < fields.length; i++) {
            // 获取属性的名字
            String name = fields[i].getName();
            // 将属性的首字符大写，方便构造get，set方法
            name = name.substring(0, 1).toUpperCase() + name.substring(1);
            // 获取属性的类型
            String type = fields[i].getGenericType().toString();
//            System.out.println(name+" "+type);
            // 如果type是类类型，则前面包含"class "，后面跟类名
            if (type.equals("class java.lang.String")) {
                Method m = object.getClass().getMethod("get" + name);
                // 调用getter方法获取属性值
                String value = (String) m.invoke(object);
                if (value == null) {
                    Class[] parameterTypes = new Class[1];
                    parameterTypes[0] = fields[i].getType();
                    m = object.getClass().getMethod("set" + name, parameterTypes);
                    String string = new String("");
                    Object[] objects = new Object[1];
                    objects[0] = string;
                    m.invoke(object, objects);
                }
            }else if(type.equals("class java.math.BigDecimal")){
                Method m = object.getClass().getMethod("get" + name);
                // 调用getter方法获取属性值
                BigDecimal value = (BigDecimal) m.invoke(object);
                if (value == null) {
                    Class[] parameterTypes = new Class[1];
                    parameterTypes[0] = fields[i].getType();
                    m = object.getClass().getMethod("set" + name, parameterTypes);
                    BigDecimal bigDecimal = new BigDecimal(0);
                    Object[] objects = new Object[1];
                    objects[0] = bigDecimal;
                    m.invoke(object, objects);
                }
            }else if(type.equals(" class java.lang.Integer")){
                Method m = object.getClass().getMethod("get" + name);
                // 调用getter方法获取属性值
                Integer value = (Integer) m.invoke(object);
                if (value == null) {
                    Class[] parameterTypes = new Class[1];
                    parameterTypes[0] = fields[i].getType();
                    m = object.getClass().getMethod("set" + name, parameterTypes);
                    Integer integer = new Integer(0);
                    Object[] objects = new Object[1];
                    objects[0] = integer;
                    m.invoke(object, objects);
                }
            }
            //将形参object类中在com.yu.killnull包下的引用一块遍历修改
            if (type.contains("class com.yu.killnull")) {
                Method m = object.getClass().getMethod("get" + name);
                // 调用getter方法获取属性值
                Object value = m.invoke(object);
                killNull(value);
            }
        }
        return object;

    }
    public ResultModel uploadGoodsTrace(String url,String typeNum, GoodstrackedRecordTopPublicF6 order) {
        ResultModel reModel=null;
        try{
            QuickPay model = new QuickPay();
            String errMsg = createModelByOrder(model,order);
            if(StringUtils.isEmpty(errMsg)){
                 reModel=com.fy56.utils.TrackCenterSender.addOrder(JSONObject.toJSONString(model));
                log.info(" --- addOrder参数:" + JSONObject.toJSONString(model)+" 结果:"+JSONObject.toJSONString(reModel));
                if(100==reModel.getCode()){
                    TyResultModel content= JSON.parseObject(reModel.getObject().toString(),TyResultModel.class);
                    if("SUCCESS".equals(content.getReturnCode())){
                        subService.updateTop(order.getConsignmentbillnumber(),content.getTrackingNo(),order.getOrganizationcode(),order.getConsignmentbillmasterid());
                    }
                }else{
                    subService.updateTop(order.getConsignmentbillnumber(),"失败",order.getOrganizationcode(),order.getConsignmentbillmasterid());
                }
            }
        }catch (Exception e){
            log.info("--同步主订单失败,param："+JSONObject.toJSONString(order)+" error:"+e.getMessage());
        }
        return  reModel;
    }
    public String insert(String sql) {
        subService.insert(sql);
        return  null;
    }
    /**
     * 根据订单信息构筑对象
     *
     * @param model
     * @param order
     * @return
     */
    private String createModelByOrder(QuickPay model,GoodstrackedRecordTopPublicF6 order) {
        String newFlag="";
        model.setNewFlag(newFlag);
        model.setHeadTenant(order.getHeadquarterscode());
        model.setTenant(order.getConsignmentcode());
        String password="";
        if(order.getConsignmentpassword()!=null&&order.getConsignmentpassword().length()!=0){
            password=MD5.digest(order.getConsignmentpassword());
        }
        if(password!=null&&password.length()!=0){
            model.setTenantPass(password.toLowerCase());
        }
        model.setCreateType(order.getCreatetype());
        model.setOrderNo(order.getConsignmentbillnumber());
        model.setHandleWay(0);
        model.setUniqueOrderNo("F6"+order.getOrganizationcode()+order.getConsignmentbillnumber());
        model.setTrackingNo(order.getTraceplatformid());
        if(StringUtils.isNotEmpty(order.getTraceplatformid())){
            model.setFunOption("modify");
        }
        setOrderJsonData(model,order);
        return null;
    }
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
    /**
     * 根据订单对象设置信息
     *
     * @param model
     * @param order
     */
    public static void setOrderJsonData(QuickPay model, GoodstrackedRecordTopPublicF6 order){

        //初始化jsonData
        Map<String,Object> jsonData = Maps.newHashMap();
        //报文版本
        jsonData.put("documentVersionNumber","V1.0");
        //发送方代码-到货公司金融代码
        jsonData.put("senderCode",model.getTenant());
        //信息发送时间-默认当期时间
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String xtsj = sFormat.format(new Date());
        jsonData.put("messageSendingDateTime", DateTimeUtil.getCurrDate14());

        /*---设置body部分---*/
        Map<String,Object> body = Maps.newHashMap();
        //托运单号-票号
        body.put("shippingNoteNumber",order.getConsignmentbillnumber());
        //手工单号
        body.put("originalDocumentNumber",order.getManualnumber());
        //货号
        body.put("goodsSelfNumber",order.getGoodsnumber());
        //内部标识 帐套名称
        body.put("inHouseIdentifier", order.getOrganizationcode());
        //托运日期-开票日期
        String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getConsignmentbilldate());
        body.put("consignmentDateTime", DateTimeUtil.getFormatDate(DateTimeUtil.getFormatDate(date),DateTimeUtil.TIME_FORMAT_14));
        //付款方式代码
        body.put("paymentMethodcode",getPayment(order.getPaymentmethod()));//getPayment(FYStringUtil.getPayment(order.getPayment()))
        //货币种类
        body.put("priceCurrencyCode","CNY");
        //备注
        body.put("remark",order.getConsignmentbillremark());
        jsonData.put("body", body);

        /*---设置装货方信息：consignorInfo部分---*/
        Map<String,Object> consignorInfo = Maps.newHashMap();
        //发货人代码
        consignorInfo.put("consignorCode",StringUtils.isNotEmpty(order.getConsignorcompanycode()) ? order.getConsignorcompanycode() : "未知");
        //装货联系人姓名
        consignorInfo.put("consignorName",StringUtils.isNotEmpty(order.getConsignor()) ? order.getConsignor() : "未知");
        //发货人身份证号
        consignorInfo.put("consignorIDCard","");//暂无
        //发货人银行卡号
        String bankCardNo="";
        if(order.getAccount()!=null&&order.getAccount().length()!=0){
            bankCardNo=order.getAccount();
            bankCardNo = bankCardNo.replace("null","");
        }
        if (!isNumeric(bankCardNo)){
            bankCardNo="";
        }
        consignorInfo.put("bankCardNo",bankCardNo);
        //开户行名称
        consignorInfo.put("bankCardName",order.getBankname());
        //开户行编码
        consignorInfo.put("bankCardCode","");////暂无
        //装货联系人电话
        String consignorTelephoneNumber = "未知";
        if(StringUtils.isNotEmpty(order.getConsignormobiletelephone())){
            consignorTelephoneNumber = order.getConsignormobiletelephone();
        }else if(StringUtils.isNotEmpty(order.getConsignortelephone())){
            consignorTelephoneNumber = order.getConsignortelephone();
        }
        consignorInfo.put("consignorCompanySenderCode",order.getConsignorcompanysende());
        consignorInfo.put("consignorTelephoneNumber",consignorTelephoneNumber);
        //国家行政区划名称
        consignorInfo.put("consignorCountrySubdivisionName", "未知");
        //国家行政区划代码
        consignorInfo.put("consignorCountrySubdivisionCode", "未知");
        //装货详细地址(发货公司地址)
        consignorInfo.put("placeOfLoading", order.getPickaddress());
        //要求装货日期时间（开票日期）
        consignorInfo.put("resquestedLoadingDateTime",DateTimeUtil.getFormatDate(DateTimeUtil.getFormatDate(date),DateTimeUtil.TIME_FORMAT_14));
        //发货经度
        if(order.getConsignmentlongitude()==null||"NULL".equals(order.getConsignmentlongitude().toUpperCase())){
            order.setConsignmentlongitude("");
        }
        if(order.getSendlongitude()==null||"NULL".equals(order.getSendlongitude().toUpperCase())){
            order.setSendlongitude("");
        }
        consignorInfo.put("startLongitude",StringUtils.isNotEmpty(order.getSendlongitude()) ? order.getSendlongitude() : order.getConsignmentlongitude());
        //发货纬度
        if(order.getConsignmentlatitude()==null||"NULL".equals(order.getConsignmentlatitude().toUpperCase())){
            order.setConsignmentlatitude("");
        }
        if(order.getSendlatitude()==null||"NULL".equals(order.getSendlatitude().toUpperCase())){
            order.setSendlatitude("");
        }
        consignorInfo.put("startLatitude",StringUtils.isNotEmpty(order.getSendlatitude()) ? order.getSendlatitude() : order.getConsignmentlatitude());
        jsonData.put("consignorInfo",consignorInfo);

        /*---设置收货方信息：consigneeInfo部分---*/
        Map<String,Object> consigneeInfo = Maps.newHashMap();
        //联系人姓名
        consigneeInfo.put("consigneeName",StringUtils.isNotEmpty(order.getConsignee()) ? order.getConsignee() : "未知");
        //收货人身份证号
        consigneeInfo.put("consigneeIDCard","");
        //电话号码
        String consigneeTelephoneNumber = "未知";
        if(StringUtils.isNotEmpty(order.getConsigneetelephone())){
            consigneeTelephoneNumber = order.getConsigneetelephone();
        }else if(StringUtils.isNotEmpty(order.getConsigneemobiletelephone())){
            consigneeTelephoneNumber = order.getConsigneemobiletelephone();
        }
        consigneeInfo.put("consigneeTelephoneNumber",consigneeTelephoneNumber);
        //收货人代码
        consigneeInfo.put("consigneeCode",StringUtils.isNotEmpty(order.getConsigneecompanycode()) ? order.getConsigneecompanycode() : consigneeTelephoneNumber);
        //国家行政区划名称
        consigneeInfo.put("consigneeCountrySubdivisionName","");
        //国家行政区划代码
        consigneeInfo.put("consigneeCountrySubdivisionCode","");
        //收货详细地址（1.如果是付货处理，收货人来提货，所以地址为卸货地点）
        // 2.如果是送货处理，到货公司会按开单时录的收货人地址把货送到收货人手里，这时地址为开单录的收货人地址）
        consigneeInfo.put("goodsReceiptPlace",StringUtils.isNotEmpty(order.getConsigneeaddress()) ? order.getConsigneeaddress() : order.getConsigneeaddress());
        //到货网点公司编码(到货公司金融代码)
        consigneeInfo.put("consigneeCompanySenderCode",model.getTenant());
        //收货经度
        consigneeInfo.put("endLongitude",StringUtils.isNotEmpty(order.getReceivelongitude()) ? order.getReceivelongitude() : order.getArrivallongitude());
        //收货纬度
        consigneeInfo.put("endLatitude",StringUtils.isNotEmpty(order.getReceivelatitude()) ? order.getReceivelatitude() : order.getArrivallatitude());
        jsonData.put("consigneeInfo",consigneeInfo);

        /*---设置货物信息：goodsInfo部分---*/
        List<Map<String,Object>> goodsList = Lists.newArrayList();
        Map<String,Object> goodsInfo = null;
            goodsInfo = Maps.newHashMap();
            //货物名称
            goodsInfo.put("descriptionOfGoods",order.getGoodsname());
            //商品类别
            goodsInfo.put("goodsType",12);
            //总件数
            goodsInfo.put("totalNumberOfPackages",order.getTotalnumberofpackages());
            //包装类型代码
            goodsInfo.put("packageType","CS");
            goodsList.add(goodsInfo);
        jsonData.put("goodsInfo",goodsList);

        /*---设置费用明细：priceInfo部分---*/
        Map<String,Object> priceInfo = Maps.newHashMap();
        //运费
        priceInfo.put("freightAmount",order.getTotaltransportcost());
        //代收货款 = 代收货款 - 扣付运费
        priceInfo.put("collectingFees",order.getCollectiongoodsvalue());
        //代收手续费
        double collectSvcFees=0;
        priceInfo.put("collectSvcFees",collectSvcFees);
        //闪付代收手续费
        priceInfo.put("shanPaySvcFees","");
        //保险金额
        priceInfo.put("insuranceAmount","");
        //保险费
        priceInfo.put("insuranceFees","");
        jsonData.put("priceInfo",priceInfo);

        model.setJsonData(jsonData);
    }
    public static String getPayment(String payment){
        String result = "";
        if("已付".equals(payment)){
            result = "4";
        }else if("到付".equals(payment)){
            result = "2";
        }if("月结".equals(payment)){
            result = "5";
        }else{
            result = "2";
        }
        return result;
    }
    /**
     * 把对象封装成map做为参数传给平台
     *
     * @param model
     * @return
     */
    private String setParam(QuickPay model){
        String param = "param="+ JSONObject.toJSONString(model);
        return param;
    }

    /**
     * 把对象封装成map做为参数传给平台
     *
     * @param model
     * @return
     */
    private Map<String,Object> getMapParam(QuickPay model){
        Map<String,Object> map = Maps.newHashMap();
        //map.put("param",JSONObject.toJSONString(model));
        map.put("param", JSONObject.toJSONString(model));
        return map;
    }

    /**
     * 执行上传
     *
     * @param url
     * @param param
     * @return
     */
    private String doUpload(String url,Map<String,Object> param,boolean updateTraceFlag,String ConsignmentBillNumber,String OrganizationCode,String id){
        String result = null;
        String errMsg = null;
        QuickPayContent content = null;
        FYResultModel resultModel = null;
        try {
            Map<String,String> data = null;
            //发起请求并取得返回值
            log.info(" ---doUpload 参数:" + JSON.toJSONString(param) );
            HttpRequest mRequest = HttpRequest.post(url , param, true);
            mRequest.header("Content-type", "application/x-www-form-urlencoded");
            result = mRequest.body();
            log.info(" ---doUpload 结果:" + result);
            if(StringUtils.isNotEmpty(result)){
                resultModel = JSON.parseObject(result, FYResultModel.class);
                content = JSON.parseObject(resultModel.getObject().toString(),QuickPayContent.class);
                if("SUCCESS".equals(content.getReturnCode())){
                    if(updateTraceFlag){
                        //回更订单路由（平台唯一单号更新到货物跟踪表里）
                        if(content!=null){
                            List<Map<String,Object>> list = content.getList();
                            if(list!=null){
                                for (Map<String,Object> map : list) {
                                    subService.updatePublic(ConsignmentBillNumber,map.get("uniqueNo")+"",OrganizationCode,map.get("shippingTraceId")+"");
                                }
                            }
                        }
                    }else{
                        //回更主订单（平台唯一单号更新到订单表里）
                        if(content!=null){
                            subService.updateTop(ConsignmentBillNumber,content.getTrackingNo(),OrganizationCode,id);
                        }

                    }
                }else{
                    if(updateTraceFlag){
                        subService.updatePublic(ConsignmentBillNumber,"失败",OrganizationCode,id);
                    }else{
                        subService.updateTop(ConsignmentBillNumber,"失败",OrganizationCode,id);
                    }

                }
            }else{
                errMsg = "请求失败或无返回值";
                if(updateTraceFlag){
                    subService.updatePublic(ConsignmentBillNumber,"失败",OrganizationCode,id);
                }else{
                    subService.updateTop(ConsignmentBillNumber,"失败",OrganizationCode,id);
                }
            }
        } catch (JSONException e) {
            errMsg = e.getMessage() == null ? "货物跟踪平台服务端异常！" : e.getMessage();
        } catch (Exception e) {
            errMsg = e.getMessage() == null ? "服务端异常" : e.getMessage();
        }finally {
            content = null;
            resultModel = null;
            result = null;
            return errMsg;
        }
    }
    /**
     * 设置上传订单路由参数
     *
     * @param typeNum
     * @return
     */
    private Map<String,Object> makeSubTrackingParams(String typeNum,String orderNo,GoodsPublic goodsTrace){
        QuickPay model = new QuickPay();
        model.setTenant(goodsTrace.getConsignmentcode());
        String password="";
        if(goodsTrace.getConsignmentpassword()!=null&&goodsTrace.getConsignmentpassword().length()!=0){
            password=MD5.digest(goodsTrace.getConsignmentpassword());
        }
        if(password!=null&&password.length()!=0){
            model.setTenantPass(password.toLowerCase());
        }

        model.setHeadTenant(goodsTrace.getHeadquarterscode());
        model.setHandleWay(0);
        //初始化jsonData
        Map<String,Object> jsonData = Maps.newHashMap();
        //报文版本
        jsonData.put("documentVersionNumber","V1.0");
        //信息发送时间-默认当期时间
        jsonData.put("messageSendingDateTime", DateTimeUtil.getCurrDate14());

        /*---设置body部分---*/
        List<Map<String,Object>> bodyList =Lists.newArrayList();
        if(goodsTrace!=null) {
            Map<String,Object> body = null;
                body = Maps.newHashMap();
                //货物跟踪平台主订单唯一标识
                body.put("trackingNo",goodsTrace.getTraceplatformid());
                //货物跟踪平台订单路由唯一标识
                body.put("uniqueNo",goodsTrace.getUniqueno());
                //业务变更时间
            String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(goodsTrace.getSystime());
                body.put("statusChangeDateTime",DateTimeUtil.getFormatDateTime(DateTimeUtil.getFormatDateTime(date),DateTimeUtil.TIME_FORMAT_14));
                //业务状态代码
                body.put("shippingNoteStatusCode",getStandardStateCode(goodsTrace.getTypenum(),""));
                //备注
                body.put("remark","");

                /*---取发货公司金融代码作为发送方代码，国家行政区划名称，国家行政区划代码---*/
                //发送方代码
                body.put("senderCode",StringUtils.isNotEmpty(goodsTrace.getConsignmentcode()) ? goodsTrace.getConsignmentcode() : "未知");
                //国家行政区划名称
                body.put("countrySubdivisionName",goodsTrace.getCreatecompanyname());
                //国家行政区划代码
                body.put("countrySubdivisionCode", "未知");

                /*---设置跟踪信息节点：consignorInfo部分---*/
                Map<String,Object> shippingNoteStatusInfo = Maps.newHashMap();
                //操作人
                shippingNoteStatusInfo.put("nameOfPerson",goodsTrace.getCreateoperator());
                //跟踪信息
                shippingNoteStatusInfo.put("shippingNote",goodsTrace.getInfo());
                //跟踪信息ID
                shippingNoteStatusInfo.put("shippingTraceId",goodsTrace.getRecordid());
                body.put("shippingNoteStatusInfo",shippingNoteStatusInfo);

                //司机编码
                body.put("driverCode",goodsTrace.getDrivercode());
                //司机名称
                body.put("driverName",goodsTrace.getDrivername());
                //车牌号
                body.put("carLicense",goodsTrace.getCarlicense());
                //操作经度
                if(goodsTrace.getLongitude()==null||"NULL".equals(goodsTrace.getLongitude().toUpperCase())){
                    goodsTrace.setLongitude("");
                }
                body.put("longitude",goodsTrace.getLongitude());
                //操作纬度
                if(goodsTrace.getLatitude()==null||"NULL".equals(goodsTrace.getLatitude().toUpperCase())){
                    goodsTrace.setLatitude("");
                }
                body.put("latitude",goodsTrace.getLatitude());

                bodyList.add(body);
        }
        jsonData.put("body", bodyList);
        model.setJsonData(jsonData);

        //return "param="+ JSON.toJSONString(model);

        Map<String,Object> map = Maps.newHashMap();
        map.put("param",JSON.toJSONString(model));
        return map;
    }

    /**
     * 上传订单路由
     *
     * @param url 推送平台地址
     * @param order 订单路由信息
     */
    public void uploadSubTracking(String url,GoodsPublic order){
        try{
            Map<String,Object> param = makeSubTrackingParams(order.getTypenum(),order.getConsignmentbillnumber(),order);
            if(param == null){
                log.info("订单路由上传失败");
            }else{
                String errMsg = doUpload(url + "/ohmOrderRouteManager/addOrderRoute",param,true,
                        order.getConsignmentbillmasterid(),order.getOrganizationcode(),order.getRecordid()+"");
            }
        }catch (Exception e){
            log.error("订单路由上传失败",e);
        }

    }

    /**
     *
     * @param typeNum
     * @param typeName
     * @return
     */
    public String getStandardStateCode(String typeNum,String typeName){
        String result ="";
        if ("5".equals(typeNum)){
            result="6";
        }else if ("31".equals(typeNum)
                ||"27".equals(typeNum)
                ){
            result="24";
        }else if ("72".equals(typeNum)
                ||"71".equals(typeNum)
                ||"99".equals(typeNum)){
            result="13";
        }else if ("1".equals(typeNum)
                ||"401".equals(typeNum)
                ||"402".equals(typeNum)
                ||"403".equals(typeNum)
                ||"404".equals(typeNum)
                ||"405".equals(typeNum)
                ||"408".equals(typeNum)){
            result="72";
        }else if ("73".equals(typeNum)){
            result="38";
        }else if ("3".equals(typeNum)){
            result="218";
        }else if ("75".equals(typeNum)){
            result="80";
        }else if ("406".equals(typeNum)){
            result="FYCODE_ZZ";
        }else if ("406".equals(typeNum)){
            result="100";
        }else if ("409".equals(typeNum)){
            result="941";
        }else if ("77".equals(typeNum)
                ||"36".equals(typeNum)
                ||"37".equals(typeNum)
                ||"74".equals(typeNum)
                ||"76".equals(typeNum)
                ){
            result="117";
        }else{
            result=typeNum;
        }
        return  result;

    }
    /**
     * 微信推送
     *
     * @param url 推送平台地址
     * @param order 订单信息
     */
    public void doSendInfoWx(String url,GoodsPublic order){
        try{
            Map<String, String> postParams = null;
            boolean result=false;
            String tenant = order.getWxpublicnumber();//租户
            String phone = "";//手机号
            String content = order.getInfo();//发送内容
            String ph =order.getConsignmentbillnumber();
            String type =order.getTypenum()+"";
            String wxphone = "";
            SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
            String  xtsj = sFormat.format(new Date());
            String uuid = order.getOrganizationcode() + "-" + ph+ "-" + type;//唯一标识
            uuid += "-W-"+xtsj;
            if (order.getConsignormobiletelephone()!=null&&order.getConsignormobiletelephone().length()==11){
                wxphone+=order.getConsignormobiletelephone()+",";
            }
            if (order.getConsignortelephone()!=null&&order.getConsignortelephone().length()==11){
                wxphone+=order.getConsignortelephone()+",";
            }
            if (order.getConsigneemobiletelephone()!=null&&order.getConsigneemobiletelephone().length()==11){
                wxphone+=order.getConsigneemobiletelephone()+",";
            }
            if (order.getConsigneetelephone()!=null&&order.getConsigneetelephone().length()==11){
                wxphone+=order.getConsigneetelephone()+",";
            }
            if(wxphone!=null&&wxphone.length()>0){

              try{
                  String phoneList []=wxphone.split(",");
                  if (phoneList!=null&&phoneList.length>0){
                      for (int c=0; c<phoneList.length;c++){
                          String fsphone = phoneList[c];
                          if (fsphone!=null&&fsphone.length()==11){
                              try {
                                  Map<String, String> params = Maps.newHashMap();
                                  params.put("sendType", "SMS");//发送类型
                                  params.put("bizNo", uuid);//uuid
                                  params.put("bizType",type );//业务类型
                                  params.put("supplierChannel", "4");//发送渠道
                                  params.put("appPlatform","F6");
                                  params.put("content",  content);//发送内容
                                  params.put("phone", fsphone);//电话号码
                                  params.put("tenant",tenant);//语音或微信推送账号
                                  postParams = Maps.newHashMap();
//                                  postParams.put("data", JSON.toJSONString(params));
                                  String postContent = "" + JSONObject.toJSONString(params);
                                  postContent="data=" +URLEncoder.encode(postContent,"UTF-8");
                                  log.info("租户：" + tenant + "，手机号：" + phone + "调用微信推送接口，参数为：" + postContent);//JSON.toJSONString(postParams)
                                  String rsp = WebUtils.doPost(url, postContent, "UTF-8", 10000, 10000);
                                  log.info("租户：" + tenant + "微信推送发送返回结果" + rsp );
//                                  postParams.put("data", URLEncoder.encode(""+JSON.toJSONString(params),"UTF-8"));
                              } catch (Exception e) {
                                  result = false;
                                  log.error("租户：" + tenant + "，手机号：" + fsphone + "调用发送微信推送拼接参数失败：" + e.getMessage(),e);
                                  throw new Exception("调用微信推送开始拼接参数失败");
                              }
                              try {


////                                  String postResult =WebUtils.doPost(Constants.url, postParams.toString(), JrptConstants.CHARSET_UTF8, 10000, 10000);
//                                  HttpRequest mRequest = HttpRequest.post(url , postParams, true);
//                                  mRequest.header("Content-type", "application/x-www-form-urlencoded");
//                                  String postResult = mRequest.body();
//                                  log.info("租户：" + tenant + "微信推送发送返回结果" + postResult );
                              } catch (Exception e) {
                                  result = false;
                                  log.error("租户：" + tenant + "，手机号：" + fsphone + "post调用发送微信推送接收失败：" + e.getMessage() + ExceptionUtils.getStackTrace(e),e);
                                  throw new Exception("post调用发送微信推送失败");
                              }
                          }
                      }
                  }
              }catch (Exception e){

              }
                try{
                    subService.updatePublicWx(order.getConsignmentbillmasterid(),order.getOrganizationcode(),order.getRecordid()+"");
                }catch (Exception e){

                }

            }
        }catch (Exception e){
            log.error("微信推送失败",e);
        }
    }



    /**
     * 小程序推送
     *
     * @param url 推送平台地址
     * @param order 订单信息
     */
    public void doSendInfoXcx(String url,GoodsPublic order){
        try{
            Map<String, String> postParams = null;
            boolean result=false;
            String tenant = order.getXcxpublicnumber();//租户
            String phone = "";//手机号
            String content = order.getInfo();//发送内容
            String ph =order.getConsignmentbillnumber();
            String type =order.getTypenum()+"";
            String wxphone = "";
            SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
            String  xtsj = sFormat.format(new Date());
            String uuid = order.getOrganizationcode() + "-" + ph+ "-" + type;//唯一标识
            uuid += "-W-"+xtsj;
            if (order.getConsignormobiletelephone()!=null&&order.getConsignormobiletelephone().length()==11){
                wxphone+=order.getConsignormobiletelephone()+",";
            }
            if (order.getConsignortelephone()!=null&&order.getConsignortelephone().length()==11){
                wxphone+=order.getConsignortelephone()+",";
            }
            if (order.getConsigneemobiletelephone()!=null&&order.getConsigneemobiletelephone().length()==11){
                wxphone+=order.getConsigneemobiletelephone()+",";
            }
            if (order.getConsigneetelephone()!=null&&order.getConsigneetelephone().length()==11){
                wxphone+=order.getConsigneetelephone()+",";
            }
            if(wxphone!=null&&wxphone.length()>0){

                try{
                    String phoneList []=wxphone.split(",");
                    if (phoneList!=null&&phoneList.length>0){
                        for (int c=0; c<phoneList.length;c++){
                            String fsphone = phoneList[c];
                            if (fsphone!=null&&fsphone.length()==11){
                                try {
                                    Map<String, String> params = Maps.newHashMap();
                                    params.put("sendType", "SMS");//发送类型
                                    params.put("bizNo", uuid);//uuid
                                    params.put("bizType",type );//业务类型
                                    params.put("supplierChannel", "4");//发送渠道
                                    params.put("appPlatform","F6");
                                    params.put("content",  content);//发送内容
                                    params.put("phone", fsphone);//电话号码
                                    params.put("appId",tenant);//语音或微信推送账号
                                    postParams = Maps.newHashMap();
//                                  postParams.put("data", JSON.toJSONString(params));
                                    String postContent = "" + JSONObject.toJSONString(params);
                                    postContent="data=" +URLEncoder.encode(postContent,"UTF-8");
                                    log.info("租户：" + tenant + "，手机号：" + phone + "调用小程序推送接口，参数为：" + postContent);//JSON.toJSONString(postParams)
                                    String rsp = WebUtils.doPost(url, postContent, "UTF-8", 10000, 10000);
                                    log.info("租户：" + tenant + "小程序推送发送返回结果" + rsp );
//                                  postParams.put("data", URLEncoder.encode(""+JSON.toJSONString(params),"UTF-8"));
                                } catch (Exception e) {
                                    result = false;
                                    log.error("租户：" + tenant + "，手机号：" + fsphone + "调用发送小程序推送拼接参数失败：" + e.getMessage(),e);
                                    throw new Exception("调用小程序推送开始拼接参数失败");
                                }
                                try {


////                                  String postResult =WebUtils.doPost(Constants.url, postParams.toString(), JrptConstants.CHARSET_UTF8, 10000, 10000);
//                                  HttpRequest mRequest = HttpRequest.post(url , postParams, true);
//                                  mRequest.header("Content-type", "application/x-www-form-urlencoded");
//                                  String postResult = mRequest.body();
//                                  log.info("租户：" + tenant + "微信推送发送返回结果" + postResult );
                                } catch (Exception e) {
                                    result = false;
                                    log.error("租户：" + tenant + "，手机号：" + fsphone + "post调用发送小程序推送接收失败：" + e.getMessage() + ExceptionUtils.getStackTrace(e),e);
                                    throw new Exception("post调用发送小程序推送失败");
                                }
                            }
                        }
                    }
                }catch (Exception e){

                }
                try{
                    subService.updatePublicXcx(order.getConsignmentbillmasterid(),order.getOrganizationcode(),order.getRecordid()+"");
                }catch (Exception e){

                }

            }
        }catch (Exception e){
            log.error("小程序推送失败",e);
        }
    }
}
